<template>
  <!--  元属性选择模态框-->
  <BasicModal title="选择元属性" v-bind="$attrs" @ok="handleOk" @register="registerModal">
    <div style="padding-left: 8px; font-weight: bold">当前选择：{{ curValueText }}</div>
    <InputSearch v-model:value="searchValue" style="margin: 8px; width: 95%" placeholder="search" />
    <Tree
      checkable
      v-if="treeData.length"
      v-model:checked-keys="checkedKeys"
      :tree-data="treeData"
      :check-strictly="true"
      :field-names="fieldNames"
      :expanded-keys="expandedKeys"
      :auto-expand-parent="autoExpandParent"
      @check="handleCheck"
      @expand="handleExpand"
    >
      <template #title="{ cnName: value }">
        <span v-if="value && value.indexOf(searchValue) > -1">
          {{ value.substring(0, value.indexOf(searchValue)) }}
          <span style="color: #f50">{{ searchValue }}</span>
          {{ value.substring(value.indexOf(searchValue) + searchValue.length) }}
        </span>
        <span v-else>{{ value }}</span>
      </template>
    </Tree>
    <Empty v-else />
  </BasicModal>
</template>

<script setup lang="ts">
  import { useMessage } from '@/hooks/web/useMessage';
  import { computed, inject, ref, unref, watch } from 'vue';
  import { Empty, InputSearch, Tree } from 'ant-design-vue';
  import { BasicModal, useModalInner } from '@/components/Modal';

  const props = defineProps({
    // 是否单选
    ifSingle: {
      type: Boolean,
      default: false,
    },
    // 是否必选
    ifRequired: {
      type: Boolean,
      default: false,
    },
  });

  const emits = defineEmits(['ok']);
  const { createMessage } = useMessage();

  // 当前选择的值文本
  const curValueText = computed(() => {
    return checkedNodes.value
      ?.map?.((node: any) => {
        const { cnName, displayName } = node;
        return cnName || displayName;
      })
      .join('、');
  });
  const ifFirst = ref<boolean>(true);
  // 树数据源
  const treeData: any = inject('treeData');
  // 扁平化的树数据源
  const treeFlatData: any = inject('treeFlatData');
  // 首次获取到数据时，展开树
  watch(treeData, () => {
    if (treeData.value?.length && ifFirst.value) {
      handleExpandedKeys('');
      ifFirst.value = false;
    }
  });
  // 搜索值
  const searchValue = ref<string>('');
  // 展开索引列表
  const expandedKeys = ref<any>([]);
  const autoExpandParent = ref<boolean>(true);
  // 替换树字段
  const fieldNames = ref<any>({ children: 'childBizMetaAttrList', title: 'cnName', key: 'id' });
  // 原始数据备份
  const dataBackup = ref<any>({});
  // 选取节点列表
  const checkedNodes = ref<any>([]);
  // 选取值列表
  const checkedKeys = ref<string[]>([]);
  // 事件提交时一并携带的数据
  const emitData = ref<any>();
  // 模态框配置
  const [registerModal] = useModalInner((data) => {
    dataBackup.value = data || {};
    const { bizMetaAttrId, optValueList } = data || {};
    emitData.value = data?.['emitData'];
    checkedKeys.value =
      (props.ifSingle
        ? bizMetaAttrId
          ? [bizMetaAttrId]
          : []
        : optValueList?.map?.((item: any) => item.bizMetaAttrId)) || [];
    checkedNodes.value = props.ifSingle ? (bizMetaAttrId ? [data] : []) : optValueList;
  });
  // 监听搜索值
  watch(
    searchValue,
    (value) => {
      handleExpandedKeys(value);
      searchValue.value = value;
      autoExpandParent.value = true;
    },
    {
      immediate: true,
    },
  );
  // 处理节点展开
  function handleExpandedKeys(value: any) {
    expandedKeys.value = treeFlatData.value
      .map((item: any) => {
        if (item.cnName?.indexOf?.(value) > -1) {
          return findParent(item.cnName, treeData.value)?.id;
        }
        return null;
      })
      .filter((item: any, i: number, self: any) => item && self.indexOf(item) === i);
  }
  // 查找父节点
  function findParent(cnName: string, tree: any) {
    let parent: any = {};
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      const children = node?.childBizMetaAttrList || [];
      if (children?.length) {
        if (children.some((item: any) => item.cnName === cnName)) {
          parent = node;
        } else if (findParent(cnName, children)?.id) {
          parent = findParent(cnName, children);
        }
      }
    }
    return parent;
  }
  // 展开/收起节点时触发
  function handleExpand(keys: (string | number)[]) {
    expandedKeys.value = keys;
    autoExpandParent.value = false;
  }
  // 	点击复选框触发
  function handleCheck(a: any, b: any) {
    const { checked } = a;
    const { checkedNodes: nodes } = b;
    // 如果是单选模式，取最后一个勾选值为当前值
    if (checked?.length && props.ifSingle) {
      const index = checked.length - 1;
      checkedKeys.value = [checked[index]];
      checkedNodes.value = [nodes[index]];
    } else {
      checkedNodes.value = nodes;
    }
  }
  // 确认操作
  function handleOk() {
    if (props.ifRequired && !checkedNodes.value?.length) {
      createMessage.error('请选择业务元属性！');
      return;
    }
    emits('ok', unref(checkedNodes), unref(emitData));
  }
</script>

<style scoped lang="less"></style>
